package com.speedchina.common.message.wechat.service.impl;
import com.speedchina.common.message.util.SendResult;
import com.speedchina.common.message.wechat.config.WechatProperties;
import com.speedchina.common.message.wechat.message.*;
import com.speedchina.common.message.wechat.service.WechatService;
import com.speedchina.common.message.wechat.util.WxChatbotClient;
import com.speedchina.framework.helper.Assert;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zyw
 */
@Service
public class WechatServiceImpl implements WechatService{
    @Autowired
    WechatProperties wechatConfig;
    /**
     * send anything typemessage
     * @param message
     * @return
     */
    @SneakyThrows
    public SendResult send(Message message) {
        SendResult sendResult = null;
        String[] webhooks = null;
        String webhook = wechatConfig.getUrl();
        if(webhook == null || "".equals(webhook)) {
            return new SendResult();
        }
        if(StringUtils.isNotBlank(webhook)&&StringUtils.isNotEmpty(webhook)){
            webhooks = webhook.split(",");
        }
        for (int i = 0; i < webhooks.length; i++) {
            this.verification(message);
            sendResult =WxChatbotClient.send(webhooks[i],message);
        }
        return sendResult;
    }

    @SneakyThrows
    public SendResult sendUrl(String url, Message message) {
        this.verification(message);
        return WxChatbotClient.send(url,message);
    }

    @SneakyThrows
    public SendResult sendUrls(String[] urls, Message message) {
        SendResult send = null;
        for (String url : urls) {
            send = WxChatbotClient.send(url, message);
        }
        return send;
    }

    public void verification(Message message){
        if(message instanceof TextMessage ){
            Assert.isEmpty(((TextMessage)message).getText(),"文本内容不能为空");
        }
        Assert.isEmpty(wechatConfig.getUrl(),"地址不能为空");
    }

}
